package com.zhu.salesmanagement.network;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.CRCinfoItem;
import com.zhu.salesmanagement.models.CustomerItem;
import com.zhu.salesmanagement.models.CustomerShelfsItem;
import com.zhu.salesmanagement.models.IntegrationStandardItem;
import com.zhu.salesmanagement.models.ProductCategoryItem;
import com.zhu.salesmanagement.models.PusherStoreItem;
import com.zhu.salesmanagement.models.RemindMsgItem;
import com.zhu.salesmanagement.models.SyncProductItem;
import com.zhu.salesmanagement.models.SyncTaskItem;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;

public class SyncUtils {

	public static String[] PROJECTION = new String[]{ "_id" };

	/**
	 * 保存产品大类数据
	 */
	public static void saveProductCategoryList(Context context, ArrayList<ProductCategoryItem> list){
		if(list != null){
    		String deletepcwhere = "";
    		for(int i = 0; i < list.size(); i++){
    			ProductCategoryItem item = list.get(i);
    			if(item.mType == ParseData.UPDATE){
    				long dbid = getDatabaseId(context, SalesSettings.ProductCategoryColumns.CONTENT_URI_NO_NOTIFICATION, 
    						SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID + " = \"" + item.mProductCategoryId +"\"");
    				ContentValues values = new ContentValues();
                    values.put(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_NAME, item.mProductCategoryName);
                    if(dbid == -1){
                    	values.put(SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID, item.mProductCategoryId);
                    	context.getContentResolver().insert(SalesSettings.ProductCategoryColumns.CONTENT_URI_NO_NOTIFICATION, values);
                    }else{
                    	context.getContentResolver().update(SalesSettings.ProductCategoryColumns.getContentUri(dbid, false), values, null, null);
                    }
    			}else{
    				if(deletepcwhere.length() == 0){
    					deletepcwhere = SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.mProductCategoryId + "\"";
    				}else{
    					deletepcwhere += " or " + SalesSettings.ProductCategoryColumns.PRODUCTCATEGORY_ID +" = \"" + item.mProductCategoryId + "\"";
    				}
    			}
    		}
    		if(deletepcwhere.length() > 1){
    			context.getContentResolver().delete(SalesSettings.ProductCategoryColumns.CONTENT_URI_NO_NOTIFICATION, deletepcwhere, null);
    		}
    	}
	}

	/**
	 * 保存产品数据
	 */
	public static void saveProductList(Context context, ArrayList<SyncProductItem> list){
		if(list != null){
    		String deletepwhere = "";
    		for(int i = 0; i < list.size(); i++){
    			SyncProductItem item = list.get(i);
    			if(item.mType == ParseData.UPDATE){
    				long dbid = getDatabaseId(context, SalesSettings.ProductsColumns.CONTENT_URI_NO_NOTIFICATION, 
    						SalesSettings.ProductsColumns.PRODUCT_ID + " = \"" + item.sProductID +"\"");
    				ContentValues values = new ContentValues();
                    values.put(SalesSettings.ProductsColumns.PRODUCTCATEGORY_ID, item.sProductCategoryID);
                    values.put(SalesSettings.ProductsColumns.PRODUCT_NAME, item.sProductShortName);
                    values.put(SalesSettings.ProductsColumns.PRODUCT_SORT, item.iSort);
                    if(dbid == -1){
                    	values.put(SalesSettings.ProductsColumns.PRODUCT_ID, item.sProductID);
                    	context.getContentResolver().insert(SalesSettings.ProductsColumns.CONTENT_URI_NO_NOTIFICATION, values);
                    }else{
                    	context.getContentResolver().update(SalesSettings.ProductsColumns.getContentUri(dbid, false), values, null, null);
                    }
    			}else{
    				if(deletepwhere.length() == 0){
    					deletepwhere = SalesSettings.ProductsColumns.PRODUCT_ID +" = \"" + item.sProductID + "\"";
    				}else{
    					deletepwhere += " or " + SalesSettings.ProductsColumns.PRODUCT_ID +" = \"" + item.sProductID + "\"";
    				}
    			}
    		}
    		if(deletepwhere.length() > 1){
    			context.getContentResolver().delete(SalesSettings.ProductsColumns.CONTENT_URI_NO_NOTIFICATION, deletepwhere, null);
    		}    		
    	}
	}

	/**
	 * 保存大区考核
	 */
	public static void saveIntegrationStandardList(Context context, ArrayList<IntegrationStandardItem> list){
		if(list != null){
    	    String deletewhere = "";
            for(int i = 0; i < list.size(); i++){
                IntegrationStandardItem item = list.get(i);
                if(item.mType == ParseData.UPDATE){
                    long dbid = getDatabaseId(context, SalesSettings.IntegrationStandardColumns.CONTENT_URI_NO_NOTIFICATION, 
                            SalesSettings.IntegrationStandardColumns.ITEMNO + " = \"" + item.iItemNo +"\"");
                    ContentValues values = new ContentValues();
                    values.put(SalesSettings.IntegrationStandardColumns.ITEMDES, item.sItemDescription);
                    values.put(SalesSettings.IntegrationStandardColumns.AREAID, item.sAreaID);
                    values.put(SalesSettings.IntegrationStandardColumns.AREANAME, item.sAreaName);
                    if(dbid == -1){
                        values.put(SalesSettings.IntegrationStandardColumns.ITEMNO, item.iItemNo);
                        context.getContentResolver().insert(SalesSettings.IntegrationStandardColumns.CONTENT_URI_NO_NOTIFICATION, values);
                    }else{
                    	context.getContentResolver().update(SalesSettings.IntegrationStandardColumns.getContentUri(dbid, false), values, null, null);
                    }
                }else{
                    if(deletewhere.length() == 0){
                        deletewhere = SalesSettings.IntegrationStandardColumns.ITEMNO +" = \"" + item.iItemNo + "\"";
                    }else{
                        deletewhere += " or " + SalesSettings.IntegrationStandardColumns.ITEMNO +" = \"" + item.iItemNo + "\"";
                    }
                }
            }
            if(deletewhere.length() > 1){
            	context.getContentResolver().delete(SalesSettings.IntegrationStandardColumns.CONTENT_URI_NO_NOTIFICATION, deletewhere, null);
            }           
    	}
	}

	/**
	 * 保存门店数据
	 */
	public static String saveCustomerList(Context context, ArrayList<CustomerItem> list){
		String deletecwhere = "";
		if(list != null){
    		for(int i = 0; i < list.size(); i++){
    			CustomerItem item = list.get(i);
    			if(item.mType == ParseData.UPDATE){
    			  long dbid = getDatabaseId(context, SalesSettings.CustomerSColumns.CONTENT_URI_NO_NOTIFICATION, 
    						SalesSettings.CustomerSColumns.CUSTOMER_ID + " = \"" + item.sCustomerID +"\"");
                  ContentValues values = new ContentValues();
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_NAME, item.sCustomerName);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_AREAID, item.sAreaID);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_VISITCODE, item.iVisitCategory);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_LAT, item.sLatitude);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_LNG, item.sLongitude);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_PROPERTY, item.iProperty);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_ADDRESS, item.sCustomerAddress);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_SLEVEL, item.sStoreLevel);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_SCATEGORT, item.sStoreCategory);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_DEALERID, item.sDealtEmployeeID);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_DEALERNAME, item.sDealtSalesPerson);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_CRCNEARTIME, item.sCRCNearTime);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_SCNEARTIME, item.sSCNearTime);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_ADDTIME, System.currentTimeMillis());
                  values.put(SalesSettings.CustomerSColumns.IMPORTANTINFO, item.sMsg);
                  if(dbid == -1){
                      values.put(SalesSettings.CustomerSColumns.CUSTOMER_ID, item.sCustomerID);
                      context.getContentResolver().insert(SalesSettings.CustomerSColumns.CONTENT_URI_NO_NOTIFICATION, values);
                  }else{
                	  context.getContentResolver().update(SalesSettings.CustomerSColumns.getContentUri(dbid, false), values, null, null);
                  }
    			}else{
    				if(deletecwhere.length() == 0){
    					deletecwhere = SalesSettings.CustomerSColumns.CUSTOMER_ID +" = \"" + item.sCustomerID + "\"";
    				}else{
    					deletecwhere += " or " + SalesSettings.CustomerSColumns.CUSTOMER_ID +" = \"" + item.sCustomerID + "\"";
    				}
    			}
    		}
    		if(deletecwhere.length() > 1){
    			context.getContentResolver().delete(SalesSettings.CustomerSColumns.CONTENT_URI_NO_NOTIFICATION, deletecwhere, null);
    		}
    	}
		return deletecwhere;
	}

	/**
	 * 插入门店数据
	 */
	public static void insertCustomerList(Context context, ArrayList<CustomerItem> list){
		if(list != null){
			int size = list.size();
    		for(int i = 0; i < size; i++){
    			CustomerItem item = list.get(i);
    			if(item.mType == ParseData.UPDATE){
                  ContentValues values = new ContentValues();
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_NAME, item.sCustomerName);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_AREAID, item.sAreaID);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_VISITCODE, item.iVisitCategory);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_LAT, item.sLatitude);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_LNG, item.sLongitude);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_PROPERTY, item.iProperty);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_ADDRESS, item.sCustomerAddress);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_SLEVEL, item.sStoreLevel);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_SCATEGORT, item.sStoreCategory);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_DEALERID, item.sDealtEmployeeID);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_DEALERNAME, item.sDealtSalesPerson);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_CRCNEARTIME, item.sCRCNearTime);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_SCNEARTIME, item.sSCNearTime);
                  values.put(SalesSettings.CustomerSColumns.IMPORTANTINFO, item.sMsg);
                  values.put(SalesSettings.CustomerSColumns.CUSTOMER_ID, item.sCustomerID);
                  context.getContentResolver().insert(SalesSettings.CustomerSColumns.CONTENT_URI_NO_NOTIFICATION, values);
    			}
    		}
    	}
	}

	/**
	 * 保存货架数据
	 */
	public static void saveCustomerShelfsList(Context context, ArrayList<CustomerShelfsItem> list){
		if(list != null){
    		for(int i = 0; i < list.size(); i++){
    			CustomerShelfsItem item = list.get(i);
    			String temWhere = SalesSettings.ProductShelfsColumns.CUSTOMER_ID + " = \"" + item.customerId +"\" and " + 
    			SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID + " = \"" + item.sProductCategoryID +"\"";
    			long dbid = getDatabaseId(context, SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, temWhere);
    			ContentValues values = new ContentValues();
    			values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_COUNT, item.iShelfCount);
                values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_AREA, item.iShelfArea);
                values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_LAYER, item.iShelfLayer);
                values.put(SalesSettings.ProductShelfsColumns.PRODUCTSHELF_TYPE, item.sShelfType);
    			if(dbid == -1){
                    values.put(SalesSettings.ProductShelfsColumns.CUSTOMER_ID, item.customerId);
                    values.put(SalesSettings.ProductShelfsColumns.PRODUCTCATEGORY_ID, item.sProductCategoryID);
                    context.getContentResolver().insert(SalesSettings.ProductShelfsColumns.CONTENT_URI_NO_NOTIFICATION, values);
    			}else{
    				context.getContentResolver().update(SalesSettings.ProductShelfsColumns.getContentUri(dbid, false), values, null, null);
    			}
    		}
    	}
	}

	/**
	 * 保存CRC信息
	 */
	public static void saveCRCinfoList(Context context, ArrayList<CRCinfoItem> list){
		if(list != null){
    	    for(int i = 0; i < list.size(); i++){
    	        CRCinfoItem item = list.get(i);
                String temWhere = SalesSettings.StoreCheckInfoColumns.STOREID + " = \"" + item.sCustomerID +"\" and " + 
                SalesSettings.StoreCheckInfoColumns.TYPEID + " = \"" + item.sProductCategoryID +"\"";
                long dbid = getDatabaseId(context, SalesSettings.StoreCheckInfoColumns.CONTENT_URI_NO_NOTIFICATION, temWhere);
                ContentValues values = new ContentValues();
                if(item.mInfo != null && item.mInfo.trim().length() > 1){
                	values.put(SalesSettings.StoreCheckInfoColumns.GOODS, item.mInfo);
                }
                values.put(SalesSettings.StoreCheckInfoColumns.IMPORTINFO, item.sImportantMSG);
                values.put(SalesSettings.StoreCheckInfoColumns.JINGPIN, item.sCompetitionMSG);
                values.put(SalesSettings.StoreCheckInfoColumns.DATATYPE, 0);
                if(dbid == -1){
                    values.put(SalesSettings.StoreCheckInfoColumns.STOREID, item.sCustomerID);
                    values.put(SalesSettings.StoreCheckInfoColumns.TYPEID, item.sProductCategoryID);
                    context.getContentResolver().insert(SalesSettings.StoreCheckInfoColumns.CONTENT_URI_NO_NOTIFICATION, values);
                }else{
                	context.getContentResolver().update(SalesSettings.StoreCheckInfoColumns.getContentUri(dbid, false), values, null, null);
                }
            }
    	}
	}

	/**
	 * 保存导购信息
	 */
	public static void savePusherStoreList(Context context, ArrayList<PusherStoreItem> list){
		if(list != null){
    		int psize = list.size();
        	String deletePW = "";
        	for(int i = 0; i < psize; i++){
        		PusherStoreItem item = list.get(i);
        		if(deletePW.length() == 0){
        			deletePW = SalesSettings.PusherInfoColumns.STOREID +" = \"" + item.sCustomerID + "\"";
                }else{
                	deletePW += " or " + SalesSettings.PusherInfoColumns.STOREID +" = \"" + item.sCustomerID + "\"";
                }
            }

        	if(deletePW != null && deletePW.trim().length() > 1){
        		context.getContentResolver().delete(SalesSettings.PusherInfoColumns.CONTENT_URI_NO_NOTIFICATION, deletePW, null);
        	}

    	    for(int i = 0; i < psize; i++){
    	        PusherStoreItem item = list.get(i);
                //String temWhere = SalesSettings.PusherInfoColumns.ESID + " = \"" + item.iEmployeeSId +"\"";
                //long dbid = getDatabaseId(context, SalesSettings.PusherInfoColumns.CONTENT_URI_NO_NOTIFICATION, temWhere);
                ContentValues values = new ContentValues();
                values.put(SalesSettings.PusherInfoColumns.ESNAME, item.sEmployeeName);
                values.put(SalesSettings.PusherInfoColumns.ESC, item.sEmployeeCategory);
                values.put(SalesSettings.PusherInfoColumns.ACD, item.sAccreditCategoryDescription);
                values.put(SalesSettings.PusherInfoColumns.RDATA, item.dRegisterDate);
                values.put(SalesSettings.PusherInfoColumns.MOBILE, item.sMobile);
                values.put(SalesSettings.PusherInfoColumns.STOREID, item.sCustomerID);
                //if(dbid == -1){
                    values.put(SalesSettings.PusherInfoColumns.ESID, item.iEmployeeSId);
                    context.getContentResolver().insert(SalesSettings.PusherInfoColumns.CONTENT_URI_NO_NOTIFICATION, values);
                //}else{
                    //mContext.getContentResolver().update(SalesSettings.PusherInfoColumns.getContentUri(dbid, false), values, null, null);
                //}
            }
    	}
	}

	/**
	 * 保存清单任务数据
	 */
	public static void saveTaskList(Context context, ArrayList<SyncTaskItem> list, long time){
		if(list != null){
    		for(int i = 0; i < list.size(); i++){
    			SyncTaskItem item = list.get(i);
    			ContentValues values = new ContentValues();
                values.put(SalesSettings.VisitedStoresColumns.EMPLOYEEID, item.sEmployeeID);
                values.put(SalesSettings.VisitedStoresColumns.TASKID, item.iDatingTaskID);
                values.put(SalesSettings.VisitedStoresColumns.TASTDATE, item.dPlanningDate);
                values.put(SalesSettings.VisitedStoresColumns.AEMPLOYEEID, item.sAssignedEmployeeID);
                values.put(SalesSettings.VisitedStoresColumns.ITEMNO, item.iItemNo);
                values.put(SalesSettings.VisitedStoresColumns.STOREID, item.sCustomerID);
                values.put(SalesSettings.VisitedStoresColumns.VISITCATEGOR, item.iVisitCategory);
                values.put(SalesSettings.VisitedStoresColumns.DTASKACTUALID, Util.getDatingTaskActualID(Util.mVerifyUserResult.id, item.sCustomerID, time));
                context.getContentResolver().insert(SalesSettings.VisitedStoresColumns.CONTENT_URI_NO_NOTIFICATION, values);
    		}
    	}
	}

	/**
	 * 保存提醒数据
	 */
	public static void saveRemindMsgList(Context context, ArrayList<RemindMsgItem> list){
		if(list != null){
    		for(int i = 0; i < list.size(); i++){
    			RemindMsgItem item = list.get(i);
				ContentValues values = new ContentValues();
				values.put(SalesSettings.RemindsColumns.EMPLOYEEID, item.sEmployeeID);
				values.put(SalesSettings.RemindsColumns.MESSAGEID, item.iRemindMSGID);
				values.put(SalesSettings.RemindsColumns.TEXT, item.sRemindMSGText);
				values.put(SalesSettings.RemindsColumns.TIME, item.dRemindTime);
				values.put(SalesSettings.RemindsColumns.TYPE, item.iCycleCategory);
				values.put(SalesSettings.RemindsColumns.CUSTOMERID, item.sCustomerID);
				values.put(SalesSettings.RemindsColumns.DEADTIME, item.dDeadTime);
				if(item.sCustomerID == null || item.sCustomerID.trim().length() == 0){
	                String eventid = Actions.addEvent(context,
	                        item.sRemindMSGText, "", "",
	                        item.dRemindTime,
	                        item.dRemindTime + 1000 * 60 * 60, 3,
	                        item.iCycleCategory);
	                if(Actions.DEBUG){
	                    Log.e("zhu", "eventid=" + eventid);
	                }
	                values.put(SalesSettings.RemindsColumns.EVENTID, eventid);
				}
				context.getContentResolver().insert(SalesSettings.RemindsColumns.CONTENT_URI, values);
    		}
    	}
	}

	/**
	 * 保存门店属性数据
	 */
	public static void saveStorePropertyList(Context context, List<Object> list){
		if(list.size() > 0 && Util.isEndVisit(context)){
    	    for(int i = 0; i < list.size(); i++){
    	        Map map = (Map)list.get(i);
    	        String cid = (String)map.get("sCustomerID");
    	        ContentValues values = new ContentValues();
                values.put(SalesSettings.CustomerSColumns.CUSTOMER_PROPERTY, 0);
                String where = SalesSettings.CustomerSColumns.CUSTOMER_ID +" = \'" + cid + "\'";
                context.getContentResolver().update(SalesSettings.CustomerSColumns.CONTENT_URI, values, where, null);
    	    }
    	}
	}

	/**
	 * 获取数据库主键ID
	 */
	private static long getDatabaseId(Context context, Uri uri, String where){
    	long id = -1;
    	Cursor cursor = null;
    	try{
    		cursor = context.getContentResolver().query(uri, PROJECTION, where, null, null);
    		if(cursor.getCount() > 0 && cursor.moveToFirst()){
    			id = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		if(cursor != null){
    			cursor.close();
    			cursor = null;
    		}
    		return id;
    	}
    }
}
